package 练习题;

/**
 * @author Liangyaoyun
 */
public class Stack {

    private Integer[] elementData;
    private Integer size = 0;

    /**
     * 无参构造器
     */
    public Stack() {
        elementData = new Integer[10];
    }

    /**
     * 有参构造器
     *
     * @param capacity
     */
    public Stack(int capacity) {

        if (capacity < 0) {
            throw new IllegalArgumentException("参数越界：" + capacity);
        }

        elementData = new Integer[capacity];
    }

    /**
     * 扩容
     */
    public void extendLength(int minCapacity) {
        int oldLength = elementData.length;
        int newLength = oldLength + (oldLength >> 1);
        if (newLength - minCapacity < 0) {
            newLength = minCapacity;
        }
        Integer[] tmp = new Integer[newLength];
        for (int i = 0; i < elementData.length; i++) {
            tmp[i] = elementData[i];
        }
        elementData = tmp;
    }

    /**
     * 将元素压入栈
     *
     * @param e
     */
    public void push(int e) {

        int minCapacity = (size + 1);

        //扩容
        if (minCapacity - elementData.length > 0) {
            extendLength(minCapacity);
        }

        elementData[size] = e;
        size++;
    }

    /**
     * 弹出栈顶元素
     *
     * @return
     */
    public int pop() {
        int num = elementData[size];
        size--;
        return num;
    }

    /**
     * 查看栈顶元素
     *
     * @return
     */
    public int peek() {
        return elementData[size];
    }

    /**
     * 查看栈内元素数量
     *
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 清空栈内元素
     */
    public void deleteAll() {
        for (int i = 0; i <= size; i++) {
            elementData[i] = null;
        }
        size = 0;
    }
}

